<template>
  <view class="mt-image-upload">
    <view v-for="(item, index) in fileList" :key="item.url" class="image-box" :style="{ width: width, height: height }">
      <image class="img" :src="item.url" @click="handlePreview(index)"></image>
      <image
        v-if="showDelete"
        class="delete"
        src="https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-circle-close.svg"
        @click="handleDelete(index)"
      ></image>
    </view>
    <view v-show="fileList.length < limit" @click="handleUpload">
      <slot>
        <view class="option-box" :style="{ width: width, height: height }">
          <text class="icon">+</text>
        </view>
      </slot>
    </view>
  </view>
</template>

<script setup>
import { getFileName, uploadFileBase } from '@/utils/tools';

const emits = defineEmits(['uploadChange']);

const props = defineProps({
  width: {
    type: String,
    default: '136rpx'
  },
  height: {
    type: String,
    default: '136rpx'
  },
  limit: {
    type: String,
    default: '200'
  },
  ossPath: {
    // 上传到阿里云的路径，传一个文件夹目录名称
    type: String,
    default: 'upload'
  },
  preview: {
    type: Boolean,
    default: true
  },
  replace: {
    // limit 为 1 的时候，是否替换之前的图片
    type: Boolean,
    default: false
  },
  showDelete: {
    type: Boolean,
    default: true
  }
});

const fileList = defineModel({ type: Array, default: () => [] });

function handlePreview(index) {
  if (props.replace && props.limit === '1') {
    handleUpload();
    return;
  }
  if (!props.preview) return;
  const urls = fileList.value.map((son) => son.url);
  uni.previewImage({
    current: Number(index),
    loop: true,
    urls
  });
}

function handleDelete(index) {
  fileList.value.splice(index, 1);
}

function handleUpload() {
  let maxCount = Number(props.limit) - fileList.value.length;

  uni.chooseImage({
    count: maxCount > 9 ? 9 : maxCount,
    success: async (res) => {
      try {
        uni.showLoading({
          title: '文件上传中...',
          mask: true
        });
        for (let idx in res.tempFiles) {
          let name = '';
          // #ifdef H5
          name = res.tempFiles[idx].name;
          // #endif
          // #ifndef H5
          name = getFileName(res.tempFiles[idx].path);
          // #endif
          const result = await uploadFileBase(
            {
              name,
              url: res.tempFilePaths[idx]
            },
            props.ossPath
          );
          if (props.replace && props.limit === '1') {
            fileList.value = [
              {
                name,
                url: result
              }
            ];
          } else {
            fileList.value.push({
              name,
              url: result
            });
          }
        }
        emits('uploadChange');
        uni.hideLoading();
      } catch (error) {
        uni.hideLoading();
      }
    }
  });
}
</script>

<style lang="scss" scoped>
.mt-image-upload {
  display: inline-flex;
  flex-wrap: wrap;
  padding-top: 20rpx;
  .image-box {
    position: relative;
    background-color: #f7f7f7;
    margin-right: 16rpx;
    margin-bottom: 16rpx;
    .img {
      width: 100%;
      height: 100%;
    }
    .delete {
      position: absolute;
      right: -14rpx;
      top: -14rpx;
      width: 30rpx;
      height: 30rpx;
    }
  }
  .option-box {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16rpx;
    margin-bottom: 16rpx;
    border-radius: 8rpx;
    background-color: #f7f7f7;
    .icon {
      font-size: 70rpx;
      color: #d5d5d5;
      margin-top: -10rpx;
    }
  }
}
</style>
